package com.ueboot.weishop.admin.controller.user;


import com.alibaba.fastjson.JSON;
import com.ueboot.core.exception.BusinessException;
import com.ueboot.core.http.response.Response;
import com.ueboot.core.shiro.processor.ShiroProcessor;
import com.ueboot.core.utils.CaptchaUtils;
import com.ueboot.weishop.admin.controller.user.vo.LoginVo;
import com.ueboot.weishop.admin.controller.user.vo.MenuVo;
import com.ueboot.weishop.entity.role.Resources;
import com.ueboot.weishop.service.role.ResourcesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping
public class LoginController {
    static final String CAPTCHA_KEY = "SHIRO_CAPTCHA_CODE";

    @Autowired
    private ShiroProcessor shiroProcessor;

    @Autowired
    private ResourcesService resourcesService;

    @PostMapping(value = "/login")
    public Response<Void> login(@RequestBody LoginVo params, HttpServletRequest request) {
        log.info("/login  username: {}  password: {}  captcha: {}", params.getUsername(), params.getPassword(), params.getCaptcha());

        String captcha = (String) request.getSession().getAttribute(CAPTCHA_KEY);
        if (params.getCaptcha().toLowerCase().equals(captcha)) {
            this.shiroProcessor.login(params.getUsername(), params.getPassword(), params.getCaptcha());
        } else {
            request.getSession().setAttribute(CAPTCHA_KEY, null);
            throw new BusinessException("验证码不正确!");
        }

        return new Response<>().message("登录成功");
    }

    @GetMapping(value = "/login")
    public Response<Void> login() {
        log.info("/login get");
        throw new UnauthenticatedException("登录超时");
    }


    @PostMapping(value = "/logout")
    public Response<Void> logout() {
        log.info("/login out");
        this.shiroProcessor.logout();
        return new Response<>();
    }


    @RequiresAuthentication
    @RequestMapping(value = "/menus", method = RequestMethod.GET)
    public Response<List<MenuVo>> menus() {
        Subject currentUser = SecurityUtils.getSubject();
        String username = (String) currentUser.getPrincipal();

        Resources[] resources = this.resourcesService.getUserResources(username);

        List<MenuVo> body = new ArrayList<>();

        for (Resources resource : resources) {
            MenuVo menu = new MenuVo();
            BeanUtils.copyProperties(resource, menu);
            menu.setThemeJson(StringUtils.isEmpty(resource.getThemeJson()) ? new HashMap() : JSON.parseObject(resource.getThemeJson(), Map.class));
            body.add(menu);
        }
        return new Response<>(body);
    }

    @RequestMapping(value = "/public/captcha", method = RequestMethod.GET)
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0L);
        response.setContentType("image/jpeg");
        String captcha = CaptchaUtils.generate(4);
        HttpSession session = request.getSession(true);
        session.setAttribute(CAPTCHA_KEY, captcha.toLowerCase());
        Integer w = 200;
        Integer h = 80;
        CaptchaUtils.outputImage(w, h, response.getOutputStream(), captcha);
    }

}
